
<template>
  <div class="table-box">
    <!-- 查询表单 -->
    <SearchForm
      v-show="isShowSearch"
      :search-form-data="searchFormData"
      >
      <template #input>
        <GridItem index="1">
          <el-form-item label="" prop="date">
            <el-date-picker
              v-model="searchFormData.date"
              type="date"
              placeholder="请选择日期"
              @focus="focus"
              @change="search"
              @keyup.enter="search"
              @panel-change="panelChange"
              :disabled-date="disabledDate"
              ref="datePickerRef"
            />
          </el-form-item>
        </GridItem>
      </template>
    </SearchForm>
    <!-- 表格主体 -->
    <div class="card table-main">
      <!-- 表格头部 操作按钮 -->
      <div class="table-header">
        <div>
          <el-row :gutter="20">
            <el-col :span="2">
              <el-input v-model="code" type="number" @input="handleCodeInput" @mousewheel.native.prevent :maxlength="6" placeholder="请输入股票代码" :disabled="isEdit?true:false" />
            </el-col>
            <el-col :span="4">
              <div class="name">
                <template v-if="stockInfo">
                  <div class="text" :class="stockInfo.change_percent>0?'red':'green'">{{ stockInfo.stock_name }}</div>
                  <div class="text" :class="stockInfo.change_percent>0?'red':'green'">{{ stockInfo.close_price}}</div>
                  <div class="text" :class="stockInfo.change_percent>0?'red':'green'">{{stockInfo.change_percent>0?'+' + stockInfo.change_percent:stockInfo.change_percent }}%</div>
                </template>
              </div>
            </el-col>
            <el-col :span="15">
              <div class="plan">
                <div class="title">下单计划</div>
                <div class="small-title">波动区间</div>
                <div class="input">
                  <el-input v-model="fluctuation_min" style="width: 80px;" type="number" @input="handleInput1" @blur="handleBlur1" @mousewheel.native.prevent :disabled="stockInfo?false:true">
                    <template #suffix> % </template>
                  </el-input>
                  <span style="margin: 0 10px;">-</span>
                  <el-input v-model="fluctuation_max" style="width: 80px;" type="number" @input="handleInput2" @blur="handleBlur2" @mousewheel.native.prevent :disabled="stockInfo?false:true">
                    <template #suffix> % </template>
                  </el-input>
                </div>
                <div class="small-title">委托百分比</div>
                  <el-input v-model="order_ratio" style="width: 70px;" type="number" @input="handleInput3" @blur="handleBlur3" @mousewheel.native.prevent :disabled="stockInfo?(fluctuation_min&&fluctuation_max)?false:true:true">
                    <template #suffix> % </template>
                  </el-input>
                  <div class="order-price" :class="order_ratio>0?'red':'green'">{{ order_price }}</div>
                <div class="small-title">份数</div>
                  <el-input v-model="quantity" style="width: 70px;" type="number" @input="handleInput4" @mousewheel.native.prevent :disabled="stockInfo?false:true" />
              </div>
            </el-col>
            <el-col v-if="isEdit" :span="1">
              <div style="display: flex;">
                <el-button type="primary" icon="CirclePlus" @click="save">保存</el-button>
                <el-button style="margin-left: 10px;" @click="reset">取消</el-button>
              </div>
            </el-col>
            <el-col v-else :span="1"><el-button type="primary" :disabled="checkResult?true:false" icon="CirclePlus" @click="add">新增</el-button></el-col>
          </el-row>
          <!-- 批量删除 -->
          <!-- <el-button type="danger" icon="Delete" @click="delMore" plain :disabled="multiple">批量删除</el-button> -->
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selectable" align="center" />
        <el-table-column type="index" label="排序" width="100" />
        <el-table-column property="code" label="股票代码" width="150" />
        <el-table-column property="stock_name" show-overflow-tooltip label="名称"/>
        <el-table-column property="close_price" label="收盘价" width="150">
          <template #default="scope">
            <span :class="scope.row.change_percent>0?'red':'green'">{{ scope.row.close_price }}</span>
          </template>
        </el-table-column>
        <el-table-column property="sector" label="板块" width="150" />
        <el-table-column property="change_percent" label="涨幅%" width="150">
          <template #default="scope">
            <span :class="scope.row.change_percent>0?'red':'green'">{{ scope.row.change_percent }}</span>
          </template>
        </el-table-column>
        <el-table-column property="item5" label="下单波动区间" width="200">
          <template #default="scope">
            <div style="display: flex;">
              <div style="margin-right: 15px;">{{ scope.row.fluctuation_min }}%</div>
              <div style="margin: 0 10px;">-</div>
              <div style="margin-right: 15px;">{{ scope.row.fluctuation_max }}%</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="order_ratio" label="委托百分比" width="200">
          <template #default="scope">
            <div style="display: flex;">
              <div style="margin-right: 15px;width: 50px;">{{ scope.row.order_ratio }}%</div>
              <div :class="scope.row.order_price>0?'red':'green'">{{ scope.row.order_price }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column property="quantity" label="份数" width="150" />
        <el-table-column property="created_at" label="创建时间" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.created_at, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template #default="scope">
            <!-- 编辑 -->
            <el-button :disabled="checkResult?true:false" type="primary" link @click="edit(scope.row)">编辑</el-button>
            <!-- 删除 -->
            <el-button :disabled="checkResult?true:false" type="danger" link @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <Pagination :total="total" :currentPage="listQuery.page" :pageSize="listQuery.pageSize" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" /> -->
    </div>
  </div>
</template>

<script setup lang="ts" name="strong">
import { ref, reactive, onMounted, watch, onUnmounted, computed } from "vue";
import GridItem from "@/components/Grid/components/GridItem.vue";
// 搜索
import SearchForm from "@/components/SearchFormNoBtn/index.vue";
import { stockListApi,stockInfoApi,stockSaveApi,getdaysApi,stockDelApi,stockEditApi} from "@/api/modules/strong";
// 分页
// import Pagination from "@/components/Pagination/index.vue";
// 新增、编辑、查看
// import AddEdit from "./components/add_edit.vue";
import { parseTime } from "@/utils/index";
import { ElMessage,ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";

const i18n = useI18n()
// 搜索数据
const searchFormData = reactive({
  date:''
});
// 股票代码
const code = ref()
const stockInfo = ref()
const handleCodeInput = (value) => {
  code.value = value.replace(/[^\d]/g, '').slice(0, 6);
}
watch(() => code.value, () => {
  if(code.value.length == 6) {
    getStockInfo()
  }
})
// 获取股票详情
const getStockInfo = () => {
  stockInfoApi(code.value).then((res:any) => {
    if(res.success) {
      stockInfo.value = res.data
    }
  })
}
const fluctuation_min = ref()
const fluctuation_max = ref()
const handleInput1 = (value) => {
  // 过滤非数字和负号的字符
  const filteredValue = value.replace(/[^-\d]/g, '');
  fluctuation_min.value = filteredValue;
}
const handleBlur1 = () => {
  // 验证逻辑：如果两个值都存在，确保min不大于max
  if (fluctuation_min.value && fluctuation_max.value) {
    const min = Number(fluctuation_min.value);
    const max = Number(fluctuation_max.value);
    if (min > max || min == max) {
      ElMessage.error('波动区间输入错误：最小值不能大于最大值，请重新填写!')
      fluctuation_min.value = '';
    }
  }
}
const handleInput2 = (value) => {
  // 过滤非数字和负号的字符
  const filteredValue = value.replace(/[^-\d]/g, '');
  fluctuation_max.value = filteredValue;
}
const handleBlur2 = (value) => {
  // 验证逻辑：如果两个值都存在，确保max不小于min
  if (fluctuation_min.value && fluctuation_max.value) {
    const min = Number(fluctuation_min.value);
    const max = Number(fluctuation_max.value);
    if (max < min || min == max) {
      ElMessage.error('波动区间输入错误：最大值不能小于最小值，请重新填写!')
      fluctuation_max.value = '';
    }
  }
}
const order_ratio = ref()
const handleInput3 = (value) => {
  order_ratio.value = value.replace(/[^-\d.]/g, '');
}
const handleBlur3 = (value) => {
  // const num = Number(order_ratio.value);
  // const min = Number(fluctuation_min.value);
  // const max = Number(fluctuation_max.value);
  // if (num<min || num>max) {
  //   ElMessage.error('委托价需在波动区间内，请重新填写!')
  //   order_ratio.value = '';
  //   order_price.value = ''
  // } else {
  //   getOrderPirce()
  // }
  getOrderPirce()
}
const order_price = ref()
const getOrderPirce = () => {
  if(stockInfo && order_ratio.value) {
    // const price = stockInfo.value.close_price * (1 + order_ratio.value / 100);
    // 将字符串转换为数字，处理可能的空值或无效值
    const closePrice = Number(stockInfo.value.close_price);
    const ratio = Number(order_ratio.value) || 0; // 无效值时默认为0
    // 计算最终价格
    const price = closePrice + closePrice * (ratio / 100);
    order_price.value = price.toFixed(2);
  } else {
    order_price.value = ''
  }
}
const quantity = ref(1)
const handleInput4 = (value) => {
  quantity.value = value.replace(/[^\d]/g, '');
}
const add = () => {
  if(!searchFormData.date) return ElMessage.error('请先选择日期！')
  if(!code.value) return ElMessage.error('请先输入股票代码！')
  if(!fluctuation_min.value) return ElMessage.error('请先输入波动区间！')
  if(!fluctuation_max.value) return ElMessage.error('请先输入波动区间！')
  if(!order_ratio.value) return ElMessage.error('请先输入委托价！')
  if(!quantity.value) return ElMessage.error('请先输入份数！')
  const data = {
    code: stockInfo.value.code,
    stock_name: stockInfo.value.stock_name,
    change_percent: stockInfo.value.change_percent,
    sector: stockInfo.value.sector,
    close_price: stockInfo.value.close_price,
    fluctuation_min: fluctuation_min.value,
    fluctuation_max: fluctuation_max.value,
    order_ratio: order_ratio.value,
    order_price: order_price.value,
    quantity: quantity.value,
    date: parseTime(searchFormData.date, '{y}-{m}-{d}'),
  }
  stockSaveApi(data).then((res:any) => {
    if(res.success) {
      ElMessage.success('新增成功！')
      getTableList()
      reset()
    }
  })
}
const reset = () => {
  code.value = ''
  stockInfo.value = ''
  fluctuation_min.value = ''
  fluctuation_max.value = ''
  order_ratio.value = ''
  order_price.value = ''
  quantity.value = 1
  isEdit.value = false
  editRow.value = ''
}
// 是否显示搜索模块
const isShowSearch = ref(true);
const search = () => {
  reset()
  getTableList()
};
const datePickerRef = ref()
const focus = () => {
  if(dataList.value.length>0) return
  const data = {
    year: parseTime(Date.now(), '{y}'),
    month: parseTime(Date.now(), '{m}')
  }
  getDateList(data)
}
const panelChange = (date, mode, view) => {
  const data = {
    year: parseTime(date, '{y}'),
    month: parseTime(date, '{m}')
  }
  getDateList(data)
};
const dataList:any = ref([])
const getDateList = (data) => {
  getdaysApi(data).then((res:any) => {
    if(res.success) {
      dataList.value = res.data.map(timestamp => {
        return parseTime(timestamp, '{y}-{m}-{d}');
      });
    }
  })
}
const disabledDate = (time: Date) => {
  return !dataList.value.includes(parseTime(time.getTime(), '{y}-{m}-{d}'))
}
const listQuery = reactive({
  page: 1, // 当前页数
  pageSize: 20, // 每页显示条数
  order: 'desc',
  column: 'createdAt'
})
// 总条数
const total = ref(0)
// 每页条数发生改变
const handleSizeChange = (val) => {
  listQuery.pageSize = val
  getTableList()
}
// 页码发生改变
const handleCurrentChange = (val) => {
  listQuery.page = val
  getTableList()
}
// 状态管理
const currentTime = ref(new Date());
let timer = ref();
// 格式化当前时间为易读字符串
const formattedCurrentTime = computed(() => {
  return currentTime.value.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
});
// 时间判断逻辑实现
const checkResult = computed(() => {
  // 如果没有选择日期，不进行判断
  if (!searchFormData.date) return null;
  
  const selected = new Date(searchFormData.date);
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 设置为今天0点
  
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1); // 明天0点
  
  // 选择的日期是今天之前
  if (selected < today) {
    return true;
  } 
  // 选择的日期是今天
  else if (selected >= today && selected < tomorrow) {
    const current = new Date(currentTime.value);
    const targetTime = new Date(searchFormData.date);
    targetTime.setHours(9, 22, 30, 0); // 设置为今天的9:22:30
    
    return current >= targetTime;
  } 
  // 选择的日期是今天之后
  else {
    return false;
  }
});
// 定时器逻辑 - 每秒更新当前时间
const updateCurrentTime = () => {
  currentTime.value = new Date();
};
// 组件挂载时启动定时器
onMounted(() => {
  // 立即更新一次时间
  updateCurrentTime();
  // 每秒更新一次
  timer.value = setInterval(updateCurrentTime, 1000);
});
// 组件卸载时清除定时器，防止内存泄漏
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
let tableData = ref()
const getTableList = () => {
  let date =  parseTime(searchFormData.date, '{y}-{m}-{d}')
  stockListApi(date).then((res:any) => {
    if(res.success) {
      tableData.value = res.data.data
    }
  })
};
const ids = ref([]); // 选中数组
const multiple = ref<boolean>(true); // 批量删除禁用
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.id);
  multiple.value = !selection.length;
};
const selectable = (row) => {
  if(row.activeFlag === 'Y') {
    return false
  } return true
}
const isEdit = ref(false)
const editRow = ref()
// 编辑
const edit = (row) => {
  console.log('row',row);
  editRow.value = row
  isEdit.value = true
  code.value = row.code
  fluctuation_min.value = row.fluctuation_min
  fluctuation_max.value = row.fluctuation_max
  order_ratio.value = row.order_ratio
  order_price.value = row.order_price
  quantity.value = row.quantity
}
const save = () => {
  if(!fluctuation_min.value) return ElMessage.error('请先输入波动区间！')
  if(!fluctuation_max.value) return ElMessage.error('请先输入波动区间！')
  if(!order_ratio.value) return ElMessage.error('请先输入委托价！')
  if(!quantity.value) return ElMessage.error('请先输入份数！')
  const data = {
    code: stockInfo.value.code,
    stock_name: stockInfo.value.stock_name,
    change_percent: stockInfo.value.change_percent,
    sector: stockInfo.value.sector,
    close_price: stockInfo.value.close_price,
    fluctuation_min: fluctuation_min.value,
    fluctuation_max: fluctuation_max.value,
    order_ratio: order_ratio.value,
    order_price: order_price.value,
    quantity: quantity.value,
    date: parseTime(searchFormData.date, '{y}-{m}-{d}'),
  }
  stockEditApi(editRow.value._id,data).then((res:any) => {
    if(res.success) {
      ElMessage.success('编辑成功！')
      getTableList()
      reset()
    }
  })
}
const del = (row) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    stockDelApi(row._id).then((res:any) => {
      if(res.success) {
        ElMessage.success('删除成功！')
        getTableList()
      }
    })
  })
}
</script>
<style lang="scss" scoped>
.name {
  height: 30px;
  background-color: #f2f3f8;
  border-radius: 15px;
  padding: 0 20px;
  line-height: 30px;
  display: flex;
  align-items: center;
  .text {
    margin-right: 15px;
  }
}
.plan {
  display: flex;
  align-items: center;
  .title {
    color: #2e92fb;
    font-weight: 500;
  }
  .small-title {
    margin: 0 20px 0 30px;
  }
  .input {
    display: flex;
    align-items: center;
  }
  .small-title {

  }
  .order-price {
    width: 50px;
    margin-left: 10px;
  }
}
.red {
  color: #f70f17;
}
.green {
  color: #57e26b;
}
</style>
